function frequency(fn, fps = 60) {
    let time = 0;
    let now = time;
    let ST;
    const newFn = (...args) => {
        clearTimeout(ST);
        now = Date.now();
        const distance = now - time;

        if (distance >= fps) {
            time = now;
            fn(...args);
        } else {
            ST = setTimeout(() => {
                newFn(...args);
            }, distance);
        }
    };
    return newFn;
}

// 全局滚动事件
export default function createScroll(dom) {
    let allScroll = {};
    function create() {
        $(dom).on(
            'scroll.public',
            frequency(() => {
                const { scrollTop, scrollHeight, clientHeight } = dom[0];
                Object.keys(allScroll).forEach(key => {
                    $.isFunction(allScroll[key]) && allScroll[key](scrollTop, scrollHeight, clientHeight);
                });
            })
        );
    }
    function appendScroll(key, callBack) {
        $.isEmptyObject(allScroll) && create(); // 第一次加进来的时候创建
        allScroll[key] = callBack;
    }
    function clear(key) {
        // 有参数 清理对应的key  没有则清除定时器
        if (key) {
            delete allScroll[key];
        } else {
            allScroll = {};
        }
        $.isEmptyObject(allScroll) && $(dom).off('scroll.public');
    }
    return {
        appendScroll,
        clear,
        allScroll,
    };
}
